<template>
  <div class="query-plan" :style="[queryPlanStyle]">
    <div class="query-column">
      <el-date-picker size="mini" v-model="value1" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
      <span class="query-btn" @click="queryPlan">搜索</span>
    </div>
    <div class="query-table">
      <el-table size="small" :data="planList" max-height="300">
        <el-table-column label="序号" width="70" prop="No">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.No }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起始时间" width="130">
          <template slot-scope="scope">
            <span style="">{{ scope.row.startTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="130">
          <template slot-scope="scope">
            <span style="">{{ scope.row.stopTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="航线名称">
          <template slot-scope="scope">
            <span style="">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="60">
          <template slot-scope="scope">
            <i class="el-icon-location-outline icon-pinter" @click.stop="location(scope.row)"></i>
            <!-- <i class="el-icon-delete icon-pinter" style="margin-left: 10px"></i> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="query-column-play">
      <div class="grid-btns-circle" :class="isanimation?'grid-btns-1':'grid-btns-2'" @click="flyanimation">
        <i class="el-icon-video-pause icon-color" v-if="isanimation"></i>
        <i class="el-icon-video-play icon-color" v-else></i>
      </div>
      <el-slider v-model="sliderValue" :min="minTime" :max="maxTime" :format-tooltip="formatTooltip" @change="handleChange" style="width: calc(100% - 100px)"> </el-slider>
      <div class="grid-btns" :class="isviewgrid?'grid-btns-1':'grid-btns-2'"  @click="viewbeidougrid">
        <i class="el-icon-s-grid icon-color"></i>
      </div>
    </div>
  </div>
</template>

<script>
import { getFlights, getFlypaths } from '@/network/static.js'
import { AirLine, FlightLine, FlightFactory } from './flightsfactory'

let ff
let startJulianDate

export default {
  name: 'ldRouteAnimation',
  props: {
    queryUrl: {
      type: String,
      default: 'http://192.168.100.90:8090/'
    },
    queryPlanStyle: {
      type: [Object, Array],
      default: () => ({ background: '#073968a1' })
    },
    uavModel: {
      type: String,
      default: require('@/assets/img/无人机.glb')
    }
  },
  data() {
    return {
      value1: '',
      minTime: 0,
      maxTime: 24 * 60,
      sliderValue: 0,
      planList: [],
      isanimation: false,
      isviewgrid: false
    }
  },
  mounted() {},
  methods: {
    formatTooltip(val) {
      var date = new Date().getTime() / 1000 / 60 + val
      if (this.value1 && this.value1.length == 2) {
        date = Cesium.JulianDate.toDate(window.Viewer.clock.startTime).getTime() / 1000 / 60 + val
      }
      var now = new Date(date * 1000 * 60)
      return this.getTimeIndex(now)
    },
    handleChange(value) {
      if (!window.Viewer.clock.shouldAnimate) {
        Cesium.JulianDate.addMinutes(window.Viewer.clock.startTime, value, window.Viewer.clock.currentTime)
      }
    },
    async queryPlan() {
      if (!ff) {
        const self = this
        ff = new FlightFactory(window.Viewer)
        ff.tickCallBack((_) => {
          if (!window.Viewer.clock.shouldAnimate) return
          self.sliderValue = Cesium.JulianDate.secondsDifference(window.Viewer.clock.currentTime, window.Viewer.clock.startTime) / 60
        })
        ff.collisionCallBack(_ => {
          this.$message.error("已选航线将在当前时间发生碰撞。");
        })
      }

      ff.Clear()

      if (!this.value1 || this.value1.length != 2) {
        this.$message.error('请选择时间范围！')
        return
      }
      var startTime = this.value1[0].getTime()
      var stopTime = this.value1[1].getTime()
      var res = await getFlights(this.queryUrl)
      var res1 = await getFlypaths(this.queryUrl)

      this.planList = []
      if (res && res.status == 200 && res1 && res1.status == 200) {
        var i = 0
        res.data.forEach((element) => {
          let sNum = new Date(element.flightdate + ' ' + element.starttime).getTime()
          let eNum = new Date(element.flightdate + ' ' + element.endtime).getTime()
          if (startTime < sNum && stopTime > eNum) {
            res1.data.forEach((ite) => {
              if (element.flypath == ite.id) {
                this.planList.push({
                  No: ++i,
                  startTime: element.flightdate + ' ' + element.starttime,
                  stopTime: element.flightdate + ' ' + element.endtime,
                  name: ite.path.name,
                  pathId: element.flypath
                })
              }
            })
          }
        })
        const queryTime = new Date().getTime()
        if (startTime < queryTime && stopTime > queryTime) {
          this.sliderValue = (queryTime - startTime) / 1000 / 60
        }

        // init fly animation
        const fs = res.data
        const as = res1.data
        const airlineidx = []
        for (const f of fs) {
          const st = new Date(f.flightdate + ' ' + f.starttime)
          const et = new Date(f.flightdate + ' ' + f.endtime)
          ff.AddFlight(new FlightLine(st, et, f.flypath))
          airlineidx.push(f.flypath)
        }

        let ii = 0
        for (const a of as) {
          if (airlineidx.indexOf(a.id) === -1) continue
          const coords = a.path.geojson.geometry.coordinates
          const cartesians = []
          for (const c of coords) {
            const car = Cesium.Cartesian3.fromDegrees(c[0], c[1], c[2])
            cartesians.push(car)
          }
          const aa = new AirLine(a.id, cartesians, this.uavModel)
          ff.AddAirLine(aa)
        }

        ff.Prepare()

        this.maxTime = Cesium.JulianDate.secondsDifference(window.Viewer.clock.stopTime, window.Viewer.clock.startTime) / 60
      }
    },
    getTimeIndex(now) {
      const yyyy = now.getFullYear()
      const MM = now.getMonth() + 1 > 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`
      const DD = now.getDate() > 9 ? now.getDate() : `0${now.getDate()}`
      const HH = now.getHours() > 9 ? now.getHours() : `0${now.getHours()}`
      const mm = now.getMinutes() > 9 ? now.getMinutes() : `0${now.getMinutes()}`
      const ss = now.getSeconds() > 9 ? now.getSeconds() : `0${now.getSeconds()}`
      return `${yyyy}-${MM}-${DD} ${HH}:${mm}`
    },
    flyanimation() {
      this.isanimation = !this.isanimation
      if (this.isanimation) ff.Start()
      else ff.Stop()
    },
    viewbeidougrid() {
      this.isviewgrid = !this.isviewgrid
      if (!ff) return
      ff.ViewGrid(this.isviewgrid)
    },
    location(data) {
      let that = this
      getFlypaths(that.queryUrl).then((res) => {
        if (res && res.data) {
          for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].id === data.pathId) {
              console.log(res.data[i].path)
              const coords = res.data[i].path.geojson.geometry.coordinates
              let poss = that.getcoords(coords, Cesium)
              let bound = Cesium.BoundingSphere.fromPoints(poss.positions)
              let height = bound.radius * 6 + poss.height
              var offset = new Cesium.HeadingPitchRange(0.0, -1.0, height)
              window.Viewer.camera.flyToBoundingSphere(bound, {
                offset: offset,
                duration: 2.0
              })
            }
          }
        }
      })
    },
    //处理坐标数据
    getcoords(d, cesium) {
      let coordsArr = [],
        positions = [],
        heightMax = null,
        heightArr = []
      for (let i = 0; i < d.length; i++) {
        const data = d[i]
        heightArr.push(data[2])
        coordsArr.push([data[0], data[1]])
      }
      coordsArr.forEach((e) => {
        let p = cesium.Cartesian3.fromDegrees(e[0], e[1], 0)
        positions.push(p)
      })
      heightMax = Math.max(...heightArr)
      return { positions: positions, height: heightMax }
    }
  },
  beforeDestroy(){
    if(ff){
      ff.Clear();
    }
  },
}
</script>

<style lang="scss" scoped>
.query-plan {
  position: absolute;
  top: 50px;
  left: 10px;
  width: 480px;
  padding: 10px;
  border: solid #0e60af 2px;
  border-radius: 10px;
}

.query-column-play {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-table {
  padding: 10px 0;
}

.query-btn {
  color: #ffffff;
  background: #008aff80;
  border: none;
  padding: 5px 15px;
  box-shadow: 0 2px #00000004;
  cursor: pointer;
  font-weight: 400;
  white-space: nowrap;
  border-radius: 2px;
  margin: 0 10px;
  text-align: center;
}

.icon-pinter {
  cursor: pointer;
}

.icon-color {
  color: #fff;
}
.grid-btns-1{
  background: #03f14e80;
}
.grid-btns-2{
  background: #008aff80;
}
.grid-btns-circle {
  padding: 6px;
  border-radius: 50%;
  cursor: pointer;
}
.grid-btns {
  padding: 6px;
  border-radius: 4px;
  cursor: pointer;
}

::v-deep {
  .el-input__inner {
    background-color: #ffffff00;
    border: 1px solid #dcdfe6;
    color: #fff;
  }

  .el-date-editor .el-range-input {
    color: #fff;
    background: #ffffff00;
  }
  .el-date-editor .el-range-separator {
    color: #fff;
  }
}

::v-deep {
  .el-table,
  .el-table__expanded-cell {
    background-color: rgba(10, 23, 32, 0.3);
  }
  .el-table th.el-table__cell {
    overflow: hidden;
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none;
    background-color: #ffffff00;
  }
  .el-table tr {
    background-color: rgba(10, 23, 32, 0.4);
  }
  .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background-color: #22ee222e;
  }
  .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.3);
    border-radius: 3px;
  }

  .el-table colgroup col[name='gutter'] {
    width: 6px !important;
  }
  .el-table__body {
    width: 100% !important;
  }
  .el-table__body tr.hover-row > td.el-table__cell {
    background-color: rgba(15, 48, 71, 0.8);
  }

  .el-table th {
    background-color: rgba(15, 48, 71, 0.8);
  }

  .el-table__body tr.hover-row > td {
    background-color: rgba(49, 54, 58, 0.8);
  }

  .current-row {
    background-color: rgb(103 194 58 / 20%) !important;
  }
  .el-table__body tr.current-row > td {
    background-color: rgba(236, 245, 255, 0);
  }
  .el-table colgroup col[name='gutter'] {
    width: 11px;
  }
  .el-table__body {
    width: 100% !important;
  }
  .el-table__row {
    color: #fff;
  }
}
</style>